<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreBarRequest;
use App\Http\Requests\UpdateBarRequest;
use App\Models\Bar;
use App\Services\BarService;
use App\Services\PostService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class BarController extends Controller
{
    public function __construct(
        private BarService $barService,
        private PostService $postService
    ) {}

    /**
     * 显示贴吧列表
     */
    public function index(Request $request): Response
    {
        $search = $request->input('search');
        $bars = $this->barService->getBarsList($search);
        $popularBars = $this->barService->getPopularBars(10);

        return Inertia::render('Bars/Index', [
            'bars' => $bars,
            'popularBars' => $popularBars,
            'filters' => [
                'search' => $search,
            ],
        ]);
    }

    /**
     * 显示创建贴吧表单
     */
    public function create(): Response
    {
        return Inertia::render('Bars/Create');
    }

    /**
     * 创建新贴吧
     */
    public function store(StoreBarRequest $request): RedirectResponse
    {
        $bar = $this->barService->createBar($request->user(), $request->validated());

        return redirect()
            ->route('bars.show', $bar)
            ->with('success', '贴吧创建成功！');
    }

    /**
     * 显示贴吧详情
     */
    public function show(Request $request, Bar $bar): Response
    {
        $bar = $this->barService->getBarDetail($bar);
        $isMember = $request->user()
            ? $this->barService->isMember($bar, $request->user())
            : false;
        $userRole = $request->user()
            ? $this->barService->getUserRole($bar, $request->user())
            : null;

        // 获取帖子列表
        $sort = $request->input('sort', 'latest');
        // 优化：在服务层批量加载点赞和收藏状态，避免N+1查询
        $posts = $this->postService->getPostsList($bar, $sort, 15, $request->user());

        return Inertia::render('Bars/Show', [
            'bar' => $bar,
            'isMember' => $isMember,
            'userRole' => $userRole,
            'posts' => $posts,
            'filters' => [
                'sort' => $sort,
            ],
        ]);
    }

    /**
     * 显示编辑贴吧表单
     */
    public function edit(Bar $bar): Response
    {
        return Inertia::render('Bars/Edit', [
            'bar' => $bar,
        ]);
    }

    /**
     * 更新贴吧信息
     */
    public function update(UpdateBarRequest $request, Bar $bar): RedirectResponse
    {
        $this->barService->updateBar($bar, $request->user(), $request->validated());

        return redirect()
            ->route('bars.show', $bar)
            ->with('success', '贴吧信息更新成功！');
    }

    /**
     * 删除贴吧
     *
     * 注意：删除逻辑暂未实现，需要在 BarService 中实现 deleteBar 方法
     */
    public function destroy(Bar $bar): RedirectResponse
    {
        $this->authorize('delete', $bar);

        // TODO: 实现贴吧删除逻辑（需要在 BarService 中添加 deleteBar 方法）
        // $this->barService->deleteBar($bar);

        return redirect()
            ->route('bars.index')
            ->with('success', '贴吧已删除');
    }

    /**
     * 加入贴吧
     */
    public function join(Request $request, Bar $bar): RedirectResponse
    {
        $request->validate([
            // 无需额外验证
        ]);

        try {
            $this->barService->joinBar($bar, $request->user());

            return back()->with('success', '成功加入贴吧！');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 退出贴吧
     */
    public function leave(Request $request, Bar $bar): RedirectResponse
    {
        try {
            $this->barService->leaveBar($bar, $request->user());

            return back()->with('success', '已退出贴吧');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }
}
